package com.example.campuscardmanagementsys;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import jakarta.servlet.http.HttpSession;
import java.sql.*;
import java.util.*;

@RestController
@CrossOrigin(origins = "http://127.0.0.1:5500", allowCredentials = "true")
@RequestMapping("/api/posts")
public class PostController {

    // 数据库连接方法
    private Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/BlogSystem?useSSL=false&useUnicode=true&characterEncoding=utf8";
        String user = "root";
        String password = "111111";
        return DriverManager.getConnection(url, user, password);
    }

    // 创建博客（需登录）
    @PostMapping
    public ResponseEntity<String> createPost(@RequestBody Map<String, String> request, HttpSession session) {
        Object userId = session.getAttribute("userId");
        if (userId == null) {
            return ResponseEntity.status(401).body("未登录");
        }

        String title = request.get("title");
        String content = request.get("content");

        String sql = "INSERT INTO Posts (UserID, Title, Content) VALUES (?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, (int) userId);
            stmt.setString(2, title);
            stmt.setString(3, content);
            stmt.executeUpdate();

            return ResponseEntity.ok("博客创建成功");

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("创建失败");
        }
    }

    // 获取所有博客列表
    @GetMapping
    public ResponseEntity<?> getAllPosts() {
        String sql = "SELECT p.PostID, p.Title, u.Username, p.CreatedAt FROM Posts p JOIN Users u ON p.UserID = u.UserID ORDER BY p.CreatedAt DESC";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            List<Map<String, Object>> posts = new ArrayList<>();
            while (rs.next()) {
                Map<String, Object> post = new HashMap<>();
                post.put("postId", rs.getInt("PostID"));
                post.put("title", rs.getString("Title"));
                post.put("author", rs.getString("Username"));
                post.put("createdAt", rs.getTimestamp("CreatedAt"));
                posts.add(post);
            }
            return ResponseEntity.ok(posts);

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("获取失败");
        }
    }

    // 获取博客详情（含 Markdown 内容）
    @GetMapping("/{postId}")
    public ResponseEntity<?> getPostDetail(@PathVariable int postId, HttpSession session) {
        Object userId = session.getAttribute("userId");

        String sql = "SELECT p.PostID, p.Title, p.Content, p.CreatedAt, u.Username FROM Posts p JOIN Users u ON p.UserID = u.UserID WHERE p.PostID = ?";
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                Map<String, Object> post = new HashMap<>();
                post.put("postId", rs.getInt("PostID"));
                post.put("title", rs.getString("Title"));
                post.put("content", rs.getString("Content")); // Markdown 原文
                post.put("author", rs.getString("Username"));
                post.put("createdAt", rs.getTimestamp("CreatedAt"));

                // 添加浏览记录
                if (userId != null) {
                    String logSql = "INSERT INTO PostViews (PostID, UserID) VALUES (?, ?)";
                    try (PreparedStatement logStmt = conn.prepareStatement(logSql)) {
                        logStmt.setInt(1, postId);
                        logStmt.setInt(2, (int) userId);
                        logStmt.executeUpdate();
                    }
                }

                return ResponseEntity.ok(post);
            } else {
                return ResponseEntity.status(404).body("博客不存在");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("查询失败");
        }
    }

    // 修改博客（作者本人或管理员）
    @PutMapping("/{postId}")
    public ResponseEntity<String> updatePost(@PathVariable int postId,
                                             @RequestBody Map<String, String> request,
                                             HttpSession session) {
        Object currentUserId = session.getAttribute("userId");
        Object role = session.getAttribute("role");

        if (currentUserId == null) return ResponseEntity.status(401).body("未登录");

        String checkSql = "SELECT UserID FROM Posts WHERE PostID = ?";
        String updateSql = "UPDATE Posts SET Title = ?, Content = ?, UpdatedAt = NOW() WHERE PostID = ?";

        try (Connection conn = getConnection();
             PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {

            checkStmt.setInt(1, postId);
            ResultSet rs = checkStmt.executeQuery();
            if (rs.next()) {
                int authorId = rs.getInt("UserID");

                // 检查权限
                if ((int) currentUserId != authorId && !"管理员".equals(role)) {
                    return ResponseEntity.status(403).body("无权限修改此博客");
                }

                try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) {
                    updateStmt.setString(1, request.get("title"));
                    updateStmt.setString(2, request.get("content"));
                    updateStmt.setInt(3, postId);
                    updateStmt.executeUpdate();
                    return ResponseEntity.ok("更新成功");
                }

            } else {
                return ResponseEntity.status(404).body("博客不存在");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("更新失败");
        }
    }

    // 删除博客（作者本人或管理员）
    @DeleteMapping("/{postId}")
    public ResponseEntity<String> deletePost(@PathVariable int postId, HttpSession session) {
        Object currentUserId = session.getAttribute("userId");
        Object role = session.getAttribute("role");

        if (currentUserId == null) return ResponseEntity.status(401).body("未登录");

        String checkSql = "SELECT UserID FROM Posts WHERE PostID = ?";
        String deleteViewsSql = "DELETE FROM PostViews WHERE PostID = ?";
        String deletePostSql = "DELETE FROM Posts WHERE PostID = ?";

        try (Connection conn = getConnection();
             PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {

            checkStmt.setInt(1, postId);
            ResultSet rs = checkStmt.executeQuery();

            if (rs.next()) {
                int authorId = rs.getInt("UserID");

                // 检查权限：只能是作者本人或管理员
                if ((int) currentUserId != authorId && !"管理员".equals(role)) {
                    return ResponseEntity.status(403).body("无权限删除此博客");
                }

                // 开启事务
                conn.setAutoCommit(false);

                try (
                        PreparedStatement deleteViewsStmt = conn.prepareStatement(deleteViewsSql);
                        PreparedStatement deletePostStmt = conn.prepareStatement(deletePostSql)
                ) {
                    // 先删除浏览记录
                    deleteViewsStmt.setInt(1, postId);
                    deleteViewsStmt.executeUpdate();

                    // 再删除博客
                    deletePostStmt.setInt(1, postId);
                    deletePostStmt.executeUpdate();

                    conn.commit();
                    return ResponseEntity.ok("删除成功");

                } catch (SQLException e) {
                    conn.rollback(); // 出错回滚
                    e.printStackTrace();
                    return ResponseEntity.status(500).body("删除失败，已回滚");
                }

            } else {
                return ResponseEntity.status(404).body("博客不存在");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("服务器错误");
        }
    }

}
